package com.stone.sys.action;

/**
 * 菜单管理
 * <pre>
 * @author：JZ
 * @since:2010/02/10
 * </pre>
 */
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.opensymphony.xwork2.Action;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TMenu;
import com.stone.sys.service.MenuService;
import com.stone.utils.JsonUtils;
import com.stone.utils.StringUtils;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;

public class MenuAction extends BaseAction {

	private static final long serialVersionUID = 865527685459140622L;

	private MenuService menuService;
	
	// 实体用于修改
	private TMenu entity = new TMenu();
	
	// 父节点
	private String parentID;
	
	private String id;
	
	private String iconCls;
	
	private String url;
	
	private String sortId;
	
	private String title;
	
	private String start;
	
	private String limit;
	
	/**
	 * 第一次进页面
	 * @return
	 */
	public String initMenu() throws AppException {
		return Action.SUCCESS;
	}
	
	/**
	 * 查询用户菜单
	 * @return
	 * @throws AppException
	 */	
	@SuppressWarnings("unchecked")
	public void getMenu() throws IOException, AppException {
		
		List<HashMap<String,Object>> listTree;
		
		// 按钮维护
		if (parentID == null) {
			
			listTree = menuService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,m.parentID as parentID", 
					"m.btnId is null",
					null,
					" order by m.parentID, m.sortId",
					"TMenu m");
			
		} else {

			listTree = menuService.getListByDHql(
					"m.id as id, m.title as text, m.qtip as qtip,"
					+ "(case when (select count(o.id) from TMenu o where o.parentID = m.id and o.btnId is null)>0 then false else true end) as leaf", 
					"m.btnId is null and m.parentID = ?",
					new Object[] {Long.parseLong(parentID)},
					" order by m.parentID, m.sortId",
					" TMenu m");
		}
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(listTree, jsonConfig);
        
        super.getResponse().getWriter().print(json.toString());
		
	}

	/**
	 * 新建或修改一条记录
	 * @return
	 * @throws AppException
	 */	
	public void save() throws IOException, AppException {
	
		if (entity.getId() == null || entity.getId() == 0) {
			List<HashMap<String,Object>>  maxSortId =  menuService.findListBySql("select (nvl(max(SORT_ID),0) + 1) as sortId from sys_menu where btn_id is null and parent_id = '" + entity.getParentID() + "'");
			entity.setSortId(Long.parseLong(String.valueOf(maxSortId.get(0).get("sortid"))));
			this.menuService.save(entity);
		} else {
			this.menuService.update(entity);
		}
		
		super.getResponse().getWriter().print("{success:true}");
	}
	
	/**
	 * 保存按钮
	 * @return
	 * @throws AppException
	 */	
	public void saveButton() throws IOException, AppException {
		
		TMenu m = new TMenu();
		m.setIconCls(iconCls);
		m.setSortId(StringUtils.isNullOrBlank(this.sortId) ? Long.parseLong("0") : Long.parseLong(this.sortId));
		m.setTitle(title);
		m.setBtnId(Long.parseLong("1"));
		m.setParentID(Long.parseLong(parentID));
		
		// 新建
		if ("".equals(id) || "0".equals(id)) {
			//m.setId(SeqUtil.getNextKey("SEQ_SYS"));
			this.menuService.save(m);
			
			// 修改
		} else {
			m.setId(Long.parseLong(id));
			this.menuService.update(m);
		}

		super.getResponse().getWriter().print("{success:true}");
	}

	/**
	 * 删除一条记录（菜单，按钮）
	 * @return
	 * @throws AppException
	 */	
	public void delete() throws IOException, AppException {
		
		this.menuService.delete(Long.parseLong(id));

		super.getResponse().getWriter().print("{success:true}");
	}
	
	/**
	 * 查询一条记录
	 * @return
	 * @throws AppException
	 */	
	public void find()  throws IOException, AppException {
		
		TMenu menu  = (TMenu) menuService.findById(Long.parseLong(id), TMenu.class.getName());
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(menu, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
	}
	
	/**
	 * 验证
	 * @return
	 * @throws AppException
	 * @throws IOException 
	 */
	public void check() throws Exception {
		
		String out = "{}";
		
		// 修改密码时验证密码
		long count = menuService.getTotalByDHql(
				"btnId is not null and parentID = ? and iconCls = ?" , 
				new Object[]{Long.parseLong(parentID),iconCls},
				"TMenu");
		
		if (count == 1) {
			out = "{success:true,m:'按钮编号重复请重新输入！'}";
		}

		super.getResponse().getWriter().print(out);
		
	}
	
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public void setParentID(String parentID) {
		this.parentID = parentID;
	}

	public void setEntity(TMenu entity) {
		this.entity = entity;
	}
	
	public TMenu getEntity() {
		return entity;
	}
	
	public void setId(String id) {
		this.id = id;
	}

	public String getStart() {
		return start == null ? "0" : start;
	}

	public void setStart(String start) {
		this.start = start;
	}

	public String getLimit() {
		return limit == null ? IConstant.PAGE_LIMIT : limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public void setIconCls(String iconCls) {
		this.iconCls = iconCls;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setSortId(String sortId) {
		this.sortId = sortId;
	}
	
	
	
}
